package de.klingbeil.hhc.client.controller;

import java.util.List;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.inject.Inject;

import de.klingbeil.hhc.client.ItemProxy;
import de.klingbeil.hhc.client.event.ItemChangedEvent;
import de.klingbeil.hhc.client.event.ItemChangedEvent.ItemChangedHandler;
import de.klingbeil.hhc.client.handler.ItemDataHandler;
import de.klingbeil.hhc.client.handler.ItemDataHandler.ItemReceiver;
import de.klingbeil.hhc.client.view.View;

public class ItemListController implements Controller {

	private final ItemListView view;
	private final ItemDataHandler itemHandler;

	private EventBus eventBus;

	public interface ItemListView extends View {
		void setItems(List<ItemProxy> items);
	}

	@Inject
	public ItemListController(ItemListView view, ItemDataHandler itemHandler,
			EventBus eventBus) {
		this.view = view;
		this.itemHandler = itemHandler;
		this.eventBus = eventBus;
		registerItemChangedHandler();
		fetchRecords();
	}

	private void fetchRecords() {
		itemHandler.findAll(new ItemReceiver() {
			@Override
			public void onSuccess(List<ItemProxy> response) {
				view.setItems(response);
			}
		});
	}

	private HandlerRegistration registerItemChangedHandler() {
		ItemChangedHandler handler = new ItemChangedHandler() {
			@Override
			public void onItemChanged(ItemChangedEvent itemChangedEvent) {
				fetchRecords();
			}
		};
		return eventBus.addHandler(ItemChangedEvent.TYPE, handler);
	}

	@Override
	public View getView() {
		return view;
	}

}
